package com.gouqi.qiojbackendcommon.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

public class JWTUtils {

    // 签名密钥
    private static final String SECRET = "gouqi";

    /**
     * 生成token
     *
     * @return token字符串
     */
    public static String generateToken(Map<String, Object> payload) {
        //创建Calendar对象
        Calendar calendar = Calendar.getInstance();
        //获取当前时间三天后的时间
        calendar.add(Calendar.DAY_OF_MONTH, 3);
        try {
            String token = JWT.create()
                    .withIssuedAt(new Date())
                    .withClaim("payload", payload)
                    .withExpiresAt(calendar.getTime())  // 过期时间
                    .sign(Algorithm.HMAC256(SECRET));  // 签名用的secret
            return token;
        } catch (JWTCreationException exception) {
            throw new RuntimeException("token获取失败");
        }
    }


    /**
     * 解析token
     *
     * @param token token字符串
     * @return 解析后的token
     */
    public static DecodedJWT parserToken(String token) {

        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT decodedJWT = null;
        decodedJWT = jwtVerifier.verify(token);
        return decodedJWT;

    }
}
